package com.codetile.batch.db;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.LineAggregator;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;

/**
 * 把数据写入文件
 */
@Component("fileItemWrite")
public class FileItemWriter {

    @Bean
    public FlatFileItemWriter<User> fileItemWriter() throws Exception {
        FlatFileItemWriter<User> writer=new FlatFileItemWriter<>();
        String path="F:\\user.txt";
        writer.setResource(new FileSystemResource(path));

        //把一个对象转换为一行字符串
        writer.setLineAggregator(new LineAggregator<User>() {
            ObjectMapper mapper=new ObjectMapper();
            @Override
            public String aggregate(User user) {
                String str=null;
                try {
                    str=mapper.writeValueAsString(user);
                }catch (JsonProcessingException e){
                    e.printStackTrace();
                }
                return str;
            }
        });
        writer.afterPropertiesSet();
        return writer;
    }
}
